using System;
using System.IO;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Routing;

namespace Website
{
    public static class ActionExecutedContextExtensionMethods
    {
        public static FileInfo ViewPageFileInfo(this ActionExecutedContext arg)
        {
            if (null == arg)
            {
                throw new ArgumentNullException("arg");
            }

            FileInfo file = null;

            ViewResult result = (arg.Result as ViewResult);
            if (null != result)
            {
                WebFormViewEngine engine = (result.ViewEngine as WebFormViewEngine);
                if (null != engine)
                {
                    WebFormViewLocator locator = (engine.ViewLocator as WebFormViewLocator);
                    if (null != locator)
                    {
                        RouteData data = arg.RouteData;

                        string value = String.Format(
                            CultureInfo.InvariantCulture,
                            locator.ViewLocationFormats[0],
                            data.Values["Action"].ToString(),
                            data.Values["Controller"].ToString());

                        file = new FileInfo(arg.HttpContext.Server.MapPath(value));
                    }
                }
            }

            return file;
        }
    }
}